package com.wyix;

import java.lang.reflect.Constructor;

/**
 * 操作构造方法
 *
 * @author wangdx
 * @since 2025/8/5
 */
public class ConstructorDemo {
    public static void main(String[] args) throws Exception {
        Class<?> userClass = User.class;

        // 1. 获取公共构造器并创建实例
        Constructor<?> publicConstructor = userClass.getConstructor();
        User user1 = (User) publicConstructor.newInstance();

        // 2. 获取私有构造器并创建实例
        Constructor<?> privateConstructor = userClass.getDeclaredConstructor(String.class);
        // 关键：设置可访问性（突破私有限制）
        privateConstructor.setAccessible(true);
        User user2 = (User) privateConstructor.newInstance("Alice");

        System.out.println(user2.getName()); // Alice
    }
}